﻿/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


var g_securityInfos = [];


var REPORTED_CLIENT_NAME = 'gd-stocks-gadget-' + strings.VERSION_STRING;

var URL_QUOTES_INFO = 'http://www.google.com/finance/info?client=' +
    encodeURIComponent(REPORTED_CLIENT_NAME) +
    '&infotype=infoquoteall&q=';

var URL_FINANCE = 'http://finance.google.com/finance?client=' +
    encodeURIComponent(REPORTED_CLIENT_NAME) +
    '&q=';

//easter egg where a bunch of clicks will clear the options
var clearClicks = 0;



function concatTickers(splits) {

    var tickers = '';

    for (x in splits) {
        debug.trace('parsing part: ' + splits[x]);

        if (tickers != '')
            tickers += ',';

        var ticker = splits[x].split(',')[1];

        //index tickers (PRESET_INDICES)  are just the raw ticker -- don't feel like fixing that 
        if (!ticker) {
            ticker = splits[x].split(',')[0];
        }


        var item = SecurityInfo.FromString(splits[x], g_securityInfos[ticker])
        g_securityInfos[item.ticker] = item;
        tickers += item.fullticker;
    }

    return tickers;
}


function requestData(ids, callback, opt_failback) {

    clearClicks = 0;

    if (!Util.isOnline()) {
        return;
    }

    debug.trace('parsing ' + ids);

    //double/opposite sort the request to avoid loss???
    var tickers = concatTickers(ids.split('|').sort()) + ',' + concatTickers(ids.split('|').reverse());

    //pad to avoid losing tickers?
    tickers += ',.NYA';

    infosParsed = true;

    var url = URL_QUOTES_INFO + encodeURIComponent(tickers);
    var req = Util.createRequest();

    debug.trace('Opening: ' + url);
    req.open('GET', url, true);
    req.onreadystatechange = makeHandleResponse(req, callback, opt_failback);
    req.send();
}

function removeDupData(securities) {

    //remove tickers that aren't expected (padding values)
    //or are duplicates


    var found = [];

    for (var i = securities.length - 1; i >= 0; i--) {

        if (g_securityInfos[securities[i].ticker] == null) {

            securities.splice(i, 1);
        }
        else {
            if (found[securities[i].ticker] != null) {

                securities.splice(i, 1);
            }
            else {
                found[securities[i].ticker] = securities[i];
            }
        }
    }

    return securities;

}


var infosParsed = false;

function ParseSecurityInfos(data) {

    //debugger;
		var splits = data.split('|');
  
		for (x in splits )
    {
			 debug.trace('PSI parsing part: ' + splits[x]);

				item = SecurityInfo.FromString(splits[x])
			 g_securityInfos[item.ticker] = item;
	  }

	infosParsed = true;

}

function LoadInfos() {

   
  var data = options.getValue(OPTIONS_IDS_KEY);

	debug.trace('Option data loaded: ' + data);

	ParseSecurityInfos(data);
}


function makeHandleResponse(req, callback, opt_failback) {
  return function() {
    handleResponse(req, callback, opt_failback);
  };
}

function handleResponse(req, callback, opt_failback) {
  if (req.readyState != 4) {
    return;
  }

  if (req.status != 200) {
    if (opt_failback) {
      opt_failback();
    }
    return;
  }

  var data;
  var response = req.responseText;

  try {
    data = jsonParse(response);
  } catch (e) {
    debug.error(e.message);
    if (opt_failback) {
      opt_failback();
    }
    return;
  }

  var securities = [];

  for (var i = 0; i < data.length; ++i) {
    var security = new Security();
    security.load(data[i]);
    securities.push(security);
  }

  callback(securities);
}

ChartServer.comstockIntlExchCodeTbl = null;
ChartServer.intlExchTickerPrefix = null;

ChartServer.URL_STOCK_CHART = 'http://www.google.com/finance/chart?';

function ChartServer() {
}

ChartServer.initialize = function() {
  ChartServer.comstockIntlExchCodeTbl = {};
  ChartServer.comstockIntlExchCodeTbl['TSE'] = 'TOR';
  // For Shanghai stock exchange
  ChartServer.comstockIntlExchCodeTbl['SHA'] = 'SHG';
  // For Shenzhen stock exchange
  ChartServer.comstockIntlExchCodeTbl['SHE'] = 'SHE';

  ChartServer.intlExchTickerPrefix = {};
  ChartServer.intlExchTickerPrefix['SHA'] = 'E:';
  ChartServer.intlExchTickerPrefix['SHE'] = 'E:';
};

ChartServer.getChartUrl = function(security) {
  /*
  if (!ChartServer.comstockIntlExchCodeTbl) {
    ChartServer.initialize();
  }
  */

  var url = '';

  var now = new Date();
  var timestampedChartCounter = 1000000 +
      now.getHours() * 10000 +
      now.getMinutes() * 100 +
      now.getSeconds();

  var tickerForChart = security.ticker;
  /*
  if (tickerForChart == '.DJI') {
    tickerForChart = 'DJI';
  } else if (tickerForChart == '.INX') {
    tickerForChart = 'INX';
  } else if (tickerForChart == '.IXIC') {
    tickerForChart = 'COMPX';
  } else if (tickerForChart == '.NYA') {
    tickerForChart = 'NYA.X';
  }
  */

  url = ChartServer.URL_STOCK_CHART + 'q=';

  if (security.exchange) {
    url += encodeURIComponent(security.exchange + ':');
  }

  url += encodeURIComponent(tickerForChart);

  /*
  var intlExchCode = ChartServer.comstockIntlExchCodeTbl[security.exchange];
  if (intlExchCode) {
    var tickerPrefix = ChartServer.intlExchTickerPrefix[security.exchange] ||
        '';
    url = url + 't=intl' +
        '&s=' + encodeURIComponent(tickerPrefix + tickerForChart) +
        '&e=' + encodeURIComponent(intlExchCode) + '&h=1';
  } else {
    url = url + 'q=' + encodeURIComponent(security.exchange + ':' + tickerForChart);
  }
  */

  url = url + '&counter=' + encodeURIComponent(timestampedChartCounter);

  debug.trace('Retrieving chart: ' + url);

  return url;
};
